package com.chen.pfm.slice;

import com.chen.pfm.LoginAbility;
import com.chen.pfm.MainAbility;
import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.ResultVo;
import com.chen.pfm.utils.DataBaseUtil;
import com.chen.pfm.utils.HttpRequestUtil;
import com.chen.pfm.utils.MyToast;
import com.chen.pfm.utils.MyUtil;
import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import java.io.IOException;

public class RegisterAbilitySlice extends AbilitySlice {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x2022002, "RegisterAbilitySlice");
    Intent intent = null;
    TextField useridtf;//用户账号输入框
    TextField passwordtf;//密码输入框
    TextField repasswordtf;//再次密码输入框

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_register);
        //注册按钮
        Button register_but = (Button) findComponentById(ResourceTable.Id_register_but);
        Button register_cancel = (Button) findComponentById(ResourceTable.Id_register_cancel);
        useridtf = (TextField) findComponentById(ResourceTable.Id_register_userid);
        passwordtf = (TextField) findComponentById(ResourceTable.Id_register_password);
        repasswordtf = (TextField) findComponentById(ResourceTable.Id_register_repassword);
        // 为取消按钮设置点击事件回调
        register_cancel.setClickedListener(component -> {
            present(new LoginAbilitySlice(), new Intent());
        });

        // 为注册按钮设置点击事件回调
        register_but.setClickedListener(component -> {
            String userid = useridtf.getText();
            String password = passwordtf.getText();
            String repassword = repasswordtf.getText();

            if (userid == null || "".equals(userid)) {
                //账号不能为空
                MyToast.showMyToast(this, "账号不能为空!");
                return;
            } else if (password == null || "".equals(password)) {
                //密码不能为空
                MyToast.showMyToast(this, "密码不能为空!");
                return;
            } else if (repassword == null || "".equals(repassword)) {
                //确认密码不能为空
                MyToast.showMyToast(this, "确认密码不能为空!");
                return;

            } else if (!repassword.equals(password)) {
                //两次密码不一致
                MyToast.showMyToast(this, "两次密码不一致!");
                return;

            } else {

                getRemoteData(userid, password);
            }
        });
    }

    void getRemoteData(String userid, String password) {
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {//异步派发任务

            String url = MyUtil.ngrokUri + "/user/register";
            RequestBody requestBody = new FormBody.Builder()
                    .add("userid", userid)
                    .add("password", password)
                    .build();
            String getRequestjson = null;

            try {
                getRequestjson = HttpRequestUtil.sendPostRequestByOkHttp(url, requestBody);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (getRequestjson == null || getRequestjson.contains("not found")) {
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "找不到服务器，请确定服务器是否开启");
                });
                return;
            }
            HiLog.error(LABEL, "getRequestjson的信息为：" + getRequestjson);
            Gson gson = new Gson();
            ResultVo resultVo;
            try {
                resultVo = gson.fromJson(getRequestjson, ResultVo.class);

            } catch (Exception e) {
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "gson解析返回对象失败，请确定服务器是否开启");
                });
                HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                return;
            }
            if (resultVo == null) {//返回对象进行解析
                HiLog.error(LABEL, "数据解析异常，返回结果集为空！");
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "数据解析异常，返回结果集为空！");
                });
                return;
            } else if (resultVo.getCode() == 404) {
                HiLog.error(LABEL, "404错误！");
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, resultVo.getMsg());
                });
                return;
            } else if (resultVo.getCode() == 200) {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "状态码200 "+resultVo.getMsg());
                        MyToast.showMyToast(this, "正为您跳转登录页面.. ");
                    });
                    //跳转登录页面
                    this.intent = new Intent();
                    Operation operation = new Intent.OperationBuilder().withDeviceId("")
                            .withBundleName(getBundleName())
                            .withAbilityName(LoginAbility.class.getName())
                            .build();
                    this.intent.setOperation(operation);
                    startAbility(this.intent);
                }
        });

    }
}